/*
 * Copyright (c) 2014. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package com.dc.gameserver.extComponents.Kit.FlexSafeBox;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <li>@author 陈磊</li><br>
 *  <li>2012-7-20下午4:33:23</li><br>
 * <li>comments:安全沙箱  flash</li>
 */
public class SafeBox {
    private static final Logger LOG = LoggerFactory.getLogger(SafeBox.class);
	private final static int PORT = 843;
	private ServerSocket serverSocket = null;
	private ExecutorService pool = null;

	public SafeBox() throws IOException{
		serverSocket = new ServerSocket(PORT);
		pool = Executors.newCachedThreadPool();
	}
	
	public void startService(){
		while(true){
			Socket socket = null;
			try {
				socket = serverSocket.accept();
				pool.execute(new LoginServiceThread(socket));
			} catch (Exception e) {
				try{
					serverSocket.close();
				}catch(Exception ex){
				}
				
				pool.shutdown();
				return;
			}
		}
	}
}

class LoginServiceThread implements Runnable{
	
	private Socket socket;
	private BufferedReader reader;
	private BufferedWriter writer;
	private String xml;
	
	public LoginServiceThread(Socket socket){
		this.socket = socket;
		xml = "<?xml version=\"1.0\"?>\n" +
                "<cross-domain-policy>\n" +
                "<site-control permitted-cross-domain-policies=\" all \"/>\n" +
                "<allow-access-from domain=\" localhost \" to-ports=\" 9999 , 300-400 \" / >\n" +
                "</cross-domain-policy> ";
	}
	public void run(){
		try {
			InputStreamReader input = new InputStreamReader(socket.getInputStream(), "UTF-8");
			reader = new BufferedReader(input);
			OutputStreamWriter output = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
			writer = new BufferedWriter(output);

			StringBuilder data = new StringBuilder();
			int c = 0;
			while ((c = reader.read()) != -1) {
				if (c != '\0')
					data.append((char) c);
				else
					break;
			}
			String info = data.toString();
			if (info.indexOf("<policy-file-request/>")>= 0) {
				writer.write(xml + "\0");
				writer.flush();
			} else {
				writer.write("�����޷�ʶ��\0");
				writer.flush();
			}
			socket.close();

		} catch (Exception e) {
			e.printStackTrace();
			try {
			
				if (socket != null) {
					socket.close();
					socket = null;
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			} finally {
				System.gc();
			}
		}
	}
}